/*
 * Javascript file for chat.php module
 * Only contains variables and functions
 * No execution is contained in this file
 * 
 * requires jquery-1.3.2 or later
 */


var chatrefreshId=0; //id of the timer for chatrefresh

var chatupdateurl=null;
var chatrefreshurl=null;

var chatresponse=null;
var lastchatid=0; //id of latest conversation

	//replace : and ; signs in chat message
	function encodeChatMessage(str){
		var replacecolon=str.replace(":","&#58");
		var replacesemicolon=str.replace(";","&#59");
		return replacesemicolon;
	}
	function decodeChatMessage(str){
		var replacecolon=str.replace("&#58",":");
		var replacesemicolon=str.replace("&#59",";");
		return replacesemicolon;
	}

	
	//var mmToMonth = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	//convert UNIX timestamp to local time
	function showLocalDate(timestamp){
		var dt = new Date(timestamp * 1000);
		var min=dt.getMinutes();
		var mintxt=null;
		if (min<10){
			mintxt="00"; 
		} else {
			mintxt=min;
		}
		return dt.getHours()+":"+mintxt;
	}

	//display a bunch of elements with similar id format one after another
	function displayChatMessageArray(idPrefix,idArray){
		var speed="";
		if(idArray.length>0){
			if(idArray.length==1){speed="fast";}else{speed=100;}
			var id=idArray.shift();
			var what=$("#"+idPrefix+id);
			what.fadeIn(speed,
				function(){
					displayChatMessageArray(idPrefix,idArray);
				});
		}
	}
	
	//send chat message to server
	function sendChat(message){
		$.post(chatupdateurl+"&lastchat="+lastchatid,{"message":encodeChatMessage(message)});
		$("#chatinput").val("");
	}
	
	function refreshChat(){
        $.getScript(chatrefreshurl+"&lastchat="+lastchatid, 
		        function(){
        			processChatResponse();
        			
        			//hide the loading message
        			if ($("#chatloading").attr("loadstatus")=="0"){
        				$("#chatloading").fadeOut("fast",function(){$("#chatloading").remove();});
        				
        			} else {
        				$("#chatloading").attr("loadstatus","1");
        			}
        			
		        	chatresponse=null;
		        });  		
	}
	
	function processChatResponse(){
		if(chatresponse){
			var tokenized=chatresponse.split(";;");
			var pieces=null;
			var from=null;
			var to=null;
			var newdiv="";
			var idsToShow=new Array();

			contents=$("#chatarea").html();
			
			for(var i=0;i<tokenized.length;i++){
				pieces=tokenized[i].split("::");
				id=pieces[0];
				if ($('#chat-'+id).length==0){ //if the element does not exist
					name=pieces[1];
					time=pieces[2];
					message=pieces[3];

					newdiv="<div id='chat-"+id+"' class=chat1>"+
							"<span class=graytext>"+showLocalDate(time)+" </span>"+name+
							"<span class=graytext> said: </span>"+decodeChatMessage(message)+
							"</div>"+newdiv;
					idsToShow.push(id);
				}
			}
			$("#chatarea").html(newdiv+contents);
			
			//display chat messages one after another.
			displayChatMessageArray("chat-",idsToShow);
			
		}
	}
	
	function initializeChatInput(id){
		$("#createchat").mouseenter(
				function(){
					var createchat=$("#createchat");
					var inputwrap=$("#chatinputwrap");
					var top=createchat.position().top;
					var left=createchat.position().left;

					inputwrap.css("top",top+"px");
					inputwrap.css("left",left+"px");
					
					inputwrap.fadeIn("fast");
					$("#chatinput").focus();
				});
		$("#chatinputwrap").mouseleave(
			function(){
				$("#chatinputwrap").fadeOut("fast");
			});
		$("#send").click(
			function(){
				sendChat($("#chatinput").val());
			});
		$("#chatinput").keyup(
				function(e){
					switch (e.keyCode){
					case 13://enter
						sendChat($("#chatinput").val());
						break;
					case 27://escape key
						$("#input").val("");
						$("#chatinputwrap").fadeOut(100);
						break;
					default:
					}
				});
	}
	
	function initializeChat(updateurl,refreshurl,chatdivid,callback){
		
		chatupdateurl=updateurl;
		chatrefreshurl=refreshurl;
		
		initializeChatInput(chatdivid);
		
		chatrefreshId=setInterval("refreshChat();",1000);
		if(callback){
			callback();
		}
	}
